<template>
  <div ref="el" class="editor codemirror"></div>
</template>

<script setup lang="ts">
import './codemirror.css'
import { ref, onMounted, watchEffect, inject, watch } from 'vue'
import { EditorView } from '@codemirror/view'
import { EditorState } from '@codemirror/state'
import { basicSetup } from 'codemirror'
import { vue } from '@codemirror/lang-vue'

export interface Props {
  mode?: string
  value?: string
  readonly?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'htmlmixed',
  value: '',
  readonly: false
})

const emit = defineEmits<(e: 'change', value: string) => void>()

const el = ref()
const needAutoResize = inject('autoresize')
let editorView = ref(null)
let startState
const getDoc = () => {
  return editorView.value?.state.doc.toString()
}
const setDoc = (str) => {
  const cm = editorView.value
  cm?.dispatch({
    changes: { from: 0, to: cm.state.doc.length, insert: str }
  })
}
defineExpose({
  getDoc
})
onMounted(() => {
  const createEditor = (editorContainer) => {
    if (editorView.value != null) {
      editorView.value.destroy()
    }
    startState = EditorState.create({
      extensions: [
        basicSetup,
        vue(),
        EditorView.updateListener.of((v) => {
          if (v.docChanged) {
            emit('change', getDoc())
          }
        })
      ]
    })
    editorView.value = new EditorView({
      state: startState,
      parent: editorContainer
    })
  }
  // editor.on('change', () => {
  //   emit('change', getDoc())
  // })

  watchEffect(() => {
    const cur = getDoc()
    if (props.value !== cur) {
      setDoc(props.value)
    }
  })
  createEditor(el.value)
})
</script>

<style scoped lang="less">
.codemirror {
  height: calc(100% - 40px);
  border: 1px solid #d9d9d9;
}
::v-deep(.cm-editor) {
  height: 100%;
}
.codemirror::v-deep(.cm-scroller) {
  &::-webkit-scrollbar {
    height: 6px;
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 0px rgba(0, 0, 0, 0.2);
    background: var(--scrollbar-thumb-color);
  }

  &::-webkit-scrollbar-track {
    background: var(--scrollbar-track-color);
  }

  &::-webkit-scrollbar-corner {
    background: var(--scrollbar-track-color);
  }
}
.editor {
  position: relative;
  height: 100%;
  width: 100%;
  overflow: hidden;
  background-color: white;
}

.CodeMirror {
  font-family: var(--font-code);
  line-height: 1.5;
  height: 100%;
}
</style>
